﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mysoft.MyCM.Web.Controllers
{
	public abstract class MBaseController : Controller
	{
		public MBaseController()
			: base()
		{

		}

		protected override void Initialize(System.Web.Routing.RequestContext requestContext)
		{
			base.Initialize(requestContext);
			this.RequestParam = MRequestParam.InitializeRequestParam(requestContext, this.ViewData);
			// 设置SSO相关参数
			ViewBag.WindowLocation = this.RequestParam.CurrentWindowLocation;
			// 设置ViewBag中的Controller和Action参数
			ViewBag.Controller = this.RequestParam.Controller;
			ViewBag.Action = this.RequestParam.Action;
		}

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			// log begin
			LogInfo("begin");
			base.OnActionExecuting(filterContext);
		}

		protected override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			base.OnActionExecuted(filterContext);
			// log end
			LogInfo("end");
		}

		/// <summary>
		/// 页面请求参数
		/// </summary>
		protected MRequestParam RequestParam = null;

		#region 日志记录
		/// <summary>
		/// 控制器内快速记录日志，以消息级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogInfo(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Message);
		}
		/// <summary>
		/// 控制器内快速记录日志，以警告级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogWarning(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Warning);
		}
		/// <summary>
		/// 控制器内快速记录日志，以停止级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogStop(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Stop);
		}
		/// <summary>
		/// 控制器内快速记录日志，以致命级别
		/// </summary>
		/// <param name="message"></param>
		protected void LogFatal(string message)
		{
			this.writeLog(message, M.MExceptionLevel.Fatal);
		}
		/// <summary>
		/// 控制器内快速记录日志
		/// </summary>
		/// <param name="message"></param>
		/// <param name="level"></param>
		private void writeLog(string message, M.MExceptionLevel level)
		{
			Business.CMLogger.Log
				(
				this.RequestParam.RequestIndentity,
				this.RequestParam.LogonUser == null ? "unknown" : this.RequestParam.LogonUser.Code,
				this.RequestParam.RequestRemoteIP,
				string.Format("{0}.{1}", this.RequestParam.Controller, this.RequestParam.Action),
				this.ControllerContext.RequestContext.HttpContext.Request.Url.AbsoluteUri,
				message,
				level
				);
		}
		#endregion
	}
}